#include "TimePickerDialog.h"
#include <QGridLayout>
#include <QDateTime>
#include <QRadioButton>
#include <QFont>
#include <QPainter>
#include <QMouseEvent>
#include <QEventLoop>
#include <QDialog>

TimePickerDialog::TimePickerDialog(const QTime& initialTime, QWidget* parent)
    : FramelessWindow(parent)
    , m_currentTime(initialTime)
{
    setupUI();
    applyStyles();
    setTime(initialTime);
    
    // 设置窗口属性
    setFixedSize(DIALOG_WIDTH, DIALOG_HEIGHT);
    setWindowModality(Qt::ApplicationModal);
    setWindowFlags(Qt::Window | Qt::Dialog | Qt::FramelessWindowHint);  // 添加 Qt::Window 标志
    setAttribute(Qt::WA_TranslucentBackground, false);
}

TimePickerDialog::~TimePickerDialog()
{
}

QTime TimePickerDialog::selectedTime() const
{
    return m_currentTime;
}

void TimePickerDialog::setDialogTitle(const QString& title)
{
    if (m_titleLabel) {
        m_titleLabel->setText(title);
    }
}

void TimePickerDialog::setupUI()
{
    m_contentWidget = new QWidget(this);
    m_mainLayout = new QVBoxLayout(m_contentWidget);
    m_mainLayout->setSpacing(0);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    
    setupTitleBar();
    setupTimeSelector();
    setupQuickOptions();
    setupButtons();
    
    // 设置主布局
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(m_contentWidget);
}

void TimePickerDialog::setupTitleBar()
{
    // 标题栏容器
    QWidget* titleBar = new QWidget();
    titleBar->setObjectName("titleBar");
    titleBar->setFixedHeight(48);
    
    QHBoxLayout* titleLayout = new QHBoxLayout(titleBar);
    titleLayout->setContentsMargins(20, 0, 20, 0);
    titleLayout->setSpacing(12);
    
    // 标题
    m_titleLabel = new QLabel("选择时间");
    m_titleLabel->setObjectName("dialogTitle");
    QFont titleFont = m_titleLabel->font();
    titleFont.setPointSize(12);
    titleFont.setBold(true);
    m_titleLabel->setFont(titleFont);
    
    // 关闭按钮
    QPushButton* btnClose = new QPushButton("×");
    btnClose->setObjectName("titleCloseBtn");
    btnClose->setFixedSize(32, 32);
    btnClose->setCursor(Qt::PointingHandCursor);
    connect(btnClose, &QPushButton::clicked, this, &TimePickerDialog::onCancel);
    
    titleLayout->addWidget(m_titleLabel);
    titleLayout->addStretch();
    titleLayout->addWidget(btnClose);
    
    m_mainLayout->addWidget(titleBar);
    
    // 设置标题栏为可拖动区域
    setTitlebarWidgets({titleBar});
}

void TimePickerDialog::setupTimeSelector()
{
    // 时间选择器容器
    QWidget* selectorContainer = new QWidget();
    selectorContainer->setObjectName("timeSelector");
    
    QVBoxLayout* containerLayout = new QVBoxLayout(selectorContainer);
    containerLayout->setSpacing(20);
    containerLayout->setContentsMargins(30, 25, 30, 20);
    
    // 时间显示标签（大号显示）
    m_timeDisplayLabel = new QLabel("00:00");
    m_timeDisplayLabel->setObjectName("timeDisplay");
    m_timeDisplayLabel->setAlignment(Qt::AlignCenter);
    m_timeDisplayLabel->setFixedHeight(60);  // 固定高度避免截断
    QFont displayFont = m_timeDisplayLabel->font();
    displayFont.setPointSize(42);
    displayFont.setBold(true);
    m_timeDisplayLabel->setFont(displayFont);
    
    containerLayout->addWidget(m_timeDisplayLabel);
    
    // 时间选择器行
    QWidget* spinBoxContainer = new QWidget();
    QHBoxLayout* spinBoxLayout = new QHBoxLayout(spinBoxContainer);
    spinBoxLayout->setSpacing(20);
    spinBoxLayout->setContentsMargins(0, 0, 0, 0);
    
    // 小时选择器
    QVBoxLayout* hourLayout = new QVBoxLayout();
    hourLayout->setSpacing(8);
    QLabel* hourLabel = new QLabel("小时");
    hourLabel->setAlignment(Qt::AlignCenter);
    hourLabel->setObjectName("timeLabel");
    
    m_hourSpinBox = new TwoDigitSpinBox();
    m_hourSpinBox->setObjectName("timeSpinBox");
    m_hourSpinBox->setRange(0, 23);
    m_hourSpinBox->setWrapping(true);
    m_hourSpinBox->setAlignment(Qt::AlignCenter);
    m_hourSpinBox->setButtonSymbols(QAbstractSpinBox::UpDownArrows);
    m_hourSpinBox->setFixedSize(120, 65);  // 增加宽度和高度
    QFont spinFont = m_hourSpinBox->font();
    spinFont.setPointSize(20);
    spinFont.setBold(true);
    m_hourSpinBox->setFont(spinFont);
    connect(m_hourSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &TimePickerDialog::onHourChanged);
    
    hourLayout->addWidget(hourLabel);
    hourLayout->addWidget(m_hourSpinBox);
    
    // 冒号分隔符
    m_colonLabel = new QLabel(":");
    m_colonLabel->setObjectName("colonLabel");
    m_colonLabel->setAlignment(Qt::AlignCenter);
    QFont colonFont = m_colonLabel->font();
    colonFont.setPointSize(28);
    colonFont.setBold(true);
    m_colonLabel->setFont(colonFont);
    
    // 分钟选择器
    QVBoxLayout* minuteLayout = new QVBoxLayout();
    minuteLayout->setSpacing(8);
    QLabel* minuteLabel = new QLabel("分钟");
    minuteLabel->setAlignment(Qt::AlignCenter);
    minuteLabel->setObjectName("timeLabel");
    
    m_minuteSpinBox = new TwoDigitSpinBox();
    m_minuteSpinBox->setObjectName("timeSpinBox");
    m_minuteSpinBox->setRange(0, 59);
    m_minuteSpinBox->setWrapping(true);
    m_minuteSpinBox->setAlignment(Qt::AlignCenter);
    m_minuteSpinBox->setButtonSymbols(QAbstractSpinBox::UpDownArrows);
    m_minuteSpinBox->setFixedSize(120, 65);  // 增加宽度和高度
    m_minuteSpinBox->setFont(spinFont);
    connect(m_minuteSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &TimePickerDialog::onMinuteChanged);
    
    minuteLayout->addWidget(minuteLabel);
    minuteLayout->addWidget(m_minuteSpinBox);
    
    spinBoxLayout->addStretch();
    spinBoxLayout->addLayout(hourLayout);
    spinBoxLayout->addWidget(m_colonLabel, 0, Qt::AlignCenter);
    spinBoxLayout->addLayout(minuteLayout);
    spinBoxLayout->addStretch();
    
    containerLayout->addWidget(spinBoxContainer);
    
    m_mainLayout->addWidget(selectorContainer);
}

void TimePickerDialog::setupQuickOptions()
{
    // 快捷选项容器
    QWidget* quickContainer = new QWidget();
    quickContainer->setObjectName("quickOptions");

    QVBoxLayout* containerLayout = new QVBoxLayout(quickContainer);
    containerLayout->setSpacing(12);
    containerLayout->setContentsMargins(30, 15, 30, 15);

    QLabel* quickLabel = new QLabel("快捷选择");
    quickLabel->setObjectName("sectionLabel");
    containerLayout->addWidget(quickLabel);

    // 创建滚动区域包裹快捷按钮
    m_quickScrollArea = new QScrollArea();
    m_quickScrollArea->setWidgetResizable(true);
    m_quickScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_quickScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_quickScrollArea->setFrameShape(QFrame::NoFrame);
    m_quickScrollArea->setStyleSheet("QScrollArea { background: transparent; border: none; }");
    m_quickScrollArea->setMaximumHeight(150);  // 限制滚动区域最大高度

    // 快捷按钮网格
    QWidget* buttonGrid = new QWidget();
    buttonGrid->setStyleSheet("background: transparent;");
    QGridLayout* gridLayout = new QGridLayout(buttonGrid);
    gridLayout->setSpacing(10);
    gridLayout->setContentsMargins(0, 5, 0, 5);

    m_quickTimeGroup = new QButtonGroup(this);
    connect(m_quickTimeGroup, QOverload<int>::of(&QButtonGroup::idClicked),
            this, &TimePickerDialog::onQuickTimeClicked);

    // 常用时间快捷按钮
    struct QuickTime {
        QString label;
        int hour;
        int minute;
    };

    QVector<QuickTime> quickTimes = {
        {"09:00", 9, 0},   {"09:30", 9, 30},  {"10:00", 10, 0},  {"10:30", 10, 30},
        {"11:00", 11, 0},  {"11:30", 11, 30}, {"12:00", 12, 0},  {"12:30", 12, 30},
        {"14:00", 14, 0},  {"14:30", 14, 30}, {"15:00", 15, 0},  {"15:30", 15, 30},
        {"16:00", 16, 0},  {"16:30", 16, 30}, {"17:00", 17, 0},  {"17:30", 17, 30},
        {"18:00", 18, 0},  {"18:30", 18, 30}, {"19:00", 19, 0},  {"19:30", 19, 30},
    };

    int row = 0, col = 0;
    for (int i = 0; i < quickTimes.size(); ++i) {
        const auto& qt = quickTimes[i];
        QPushButton* btn = new QPushButton(qt.label);
        btn->setObjectName("quickTimeBtn");
        btn->setCursor(Qt::PointingHandCursor);
        btn->setCheckable(false);
        btn->setFixedHeight(36);
        btn->setMinimumWidth(75);

        // 将时间编码到 button id
        int timeId = qt.hour * 100 + qt.minute;
        m_quickTimeGroup->addButton(btn, timeId);

        gridLayout->addWidget(btn, row, col);

        col++;
        if (col >= 4) {  // 4列布局
            col = 0;
            row++;
        }
    }

    m_quickScrollArea->setWidget(buttonGrid);
    containerLayout->addWidget(m_quickScrollArea);

    m_mainLayout->addWidget(quickContainer);
}

void TimePickerDialog::setupButtons()
{
    // 底部按钮栏
    QWidget* buttonBar = new QWidget();
    buttonBar->setObjectName("buttonBar");
    buttonBar->setFixedHeight(64);
    
    QHBoxLayout* buttonLayout = new QHBoxLayout(buttonBar);
    buttonLayout->setContentsMargins(20, 12, 20, 12);
    buttonLayout->setSpacing(12);
    
    // 当前时间按钮
    m_btnNow = new QPushButton("当前时间");
    m_btnNow->setObjectName("secondaryBtn");
    m_btnNow->setCursor(Qt::PointingHandCursor);
    m_btnNow->setMinimumHeight(40);
    connect(m_btnNow, &QPushButton::clicked, this, &TimePickerDialog::onNowClicked);
    
    buttonLayout->addWidget(m_btnNow);
    buttonLayout->addStretch();
    
    // 取消按钮
    m_btnCancel = new QPushButton("取消");
    m_btnCancel->setObjectName("secondaryBtn");
    m_btnCancel->setCursor(Qt::PointingHandCursor);
    m_btnCancel->setMinimumWidth(100);
    m_btnCancel->setMinimumHeight(40);
    connect(m_btnCancel, &QPushButton::clicked, this, &TimePickerDialog::onCancel);
    
    // 确定按钮
    m_btnConfirm = new QPushButton("确定");
    m_btnConfirm->setObjectName("primaryBtn");
    m_btnConfirm->setCursor(Qt::PointingHandCursor);
    m_btnConfirm->setMinimumWidth(100);
    m_btnConfirm->setMinimumHeight(40);
    connect(m_btnConfirm, &QPushButton::clicked, this, &TimePickerDialog::onConfirm);
    
    buttonLayout->addWidget(m_btnCancel);
    buttonLayout->addWidget(m_btnConfirm);
    
    m_mainLayout->addWidget(buttonBar);
}

void TimePickerDialog::applyStyles()
{
    setStyleSheet(R"(
        /* 主窗口 */
        TimePickerDialog {
            background: #2C2C2E;
            border: 1px solid #3C3C3E;
            border-radius: 8px;
        }
        
        /* 标题栏 */
        QWidget#titleBar {
            background: #3C3C3E;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            border-bottom: 1px solid #555;
        }
        
        QLabel#dialogTitle {
            color: #FFFFFF;
        }
        
        QPushButton#titleCloseBtn {
            background: transparent;
            color: #AAAAAA;
            border: none;
            font-size: 24px;
            font-weight: bold;
            border-radius: 4px;
        }
        
        QPushButton#titleCloseBtn:hover {
            background: #E74C3C;
            color: #FFFFFF;
        }
        
        /* 时间选择器区域 */
        QWidget#timeSelector {
            background: #2C2C2E;
        }
        
        QLabel#timeDisplay {
            color: #4CAF50;
            padding: 10px;
        }
        
        QLabel#timeLabel {
            color: #AAAAAA;
            font-size: 11px;
            margin-bottom: 4px;
        }
        
        QLabel#colonLabel {
            color: #FFFFFF;
            padding: 0 8px;
        }
        
        /* SpinBox 样式 */
        QSpinBox#timeSpinBox {
            background: #3C3C3E;
            color: #FFFFFF;
            border: 2px solid #4CAF50;
            border-radius: 8px;
            padding: 8px 35px 8px 15px; /* 右侧留空间给按钮 */
            font-size: 20px;
            font-weight: bold;
        }
        
        QSpinBox#timeSpinBox:focus {
            border-color: #66BB6A;
            background: #454547;
        }
        
        QSpinBox#timeSpinBox::up-button {
            subcontrol-origin: border;
            subcontrol-position: right top;
            width: 32px;
            height: 32px;
            border-left: 1px solid #555;
            border-top-right-radius: 6px;
            background: #4A4A4C;
        }
        
        QSpinBox#timeSpinBox::up-button:hover {
            background: #4CAF50;
        }
        
        QSpinBox#timeSpinBox::up-button:pressed {
            background: #388E3C;
        }
        
        QSpinBox#timeSpinBox::up-arrow {
            image: url(:/resource/svg/up.svg);
            width: 16px;
            height: 16px;
        }

        QSpinBox#timeSpinBox::down-button {
            subcontrol-origin: border;
            subcontrol-position: right bottom;
            width: 32px;
            height: 32px;
            border-left: 1px solid #555;
            border-bottom-right-radius: 6px;
            background: #4A4A4C;
        }

        QSpinBox#timeSpinBox::down-button:hover {
            background: #4CAF50;
        }

        QSpinBox#timeSpinBox::down-button:pressed {
            background: #388E3C;
        }

        QSpinBox#timeSpinBox::down-arrow {
            image: url(:/resource/svg/down.svg);
            width: 16px;
            height: 16px;
        }
        
        /* 快捷选项区域 */
        QWidget#quickOptions {
            background: #2C2C2E;
            border-top: 1px solid #3C3C3E;
        }
        
        QLabel#sectionLabel {
            color: #AAAAAA;
            font-size: 11px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        QPushButton#quickTimeBtn {
            background: #3C3C3E;
            color: #FFFFFF;
            border: 1px solid #4A4A4C;
            border-radius: 8px;
            padding: 8px 16px;
            font-size: 13px;
            font-weight: 500;
        }
        
        QPushButton#quickTimeBtn:hover {
            background: #4A4A4C;
            border-color: #4CAF50;
            color: #4CAF50;
        }
        
        QPushButton#quickTimeBtn:pressed {
            background: #4CAF50;
            border-color: #4CAF50;
            color: #FFFFFF;
        }
        
        /* 底部按钮栏 */
        QWidget#buttonBar {
            background: #2C2C2E;
            border-top: 1px solid #3C3C3E;
        }
        
        QPushButton#primaryBtn {
            background: #4CAF50;
            color: #FFFFFF;
            border: none;
            border-radius: 6px;
            padding: 10px 24px;
            font-weight: bold;
            font-size: 13px;
        }
        
        QPushButton#primaryBtn:hover {
            background: #66BB6A;
        }
        
        QPushButton#primaryBtn:pressed {
            background: #388E3C;
        }
        
        QPushButton#secondaryBtn {
            background: #3C3C3E;
            color: #FFFFFF;
            border: 1px solid #555;
            border-radius: 6px;
            padding: 10px 24px;
            font-size: 13px;
        }
        
        QPushButton#secondaryBtn:hover {
            background: #4A4A4C;
            border-color: #4CAF50;
        }
        
        QPushButton#secondaryBtn:pressed {
            background: #555;
        }
    )");
}

void TimePickerDialog::updateTimeDisplay()
{
    m_timeDisplayLabel->setText(m_currentTime.toString("HH:mm"));
}

void TimePickerDialog::setTime(const QTime& time)
{
    m_currentTime = time;
    
    // 更新 SpinBox（阻止信号避免递归）
    m_hourSpinBox->blockSignals(true);
    m_minuteSpinBox->blockSignals(true);
    
    m_hourSpinBox->setValue(time.hour());
    m_minuteSpinBox->setValue(time.minute());
    
    m_hourSpinBox->blockSignals(false);
    m_minuteSpinBox->blockSignals(false);
    
    updateTimeDisplay();
}

void TimePickerDialog::onHourChanged(int hour)
{
    m_currentTime.setHMS(hour, m_currentTime.minute(), 0);
    updateTimeDisplay();
}

void TimePickerDialog::onMinuteChanged(int minute)
{
    m_currentTime.setHMS(m_currentTime.hour(), minute, 0);
    updateTimeDisplay();
}

void TimePickerDialog::onQuickTimeClicked(int id)
{
    // 从 id 解码时间（hour * 100 + minute）
    int hour = id / 100;
    int minute = id % 100;
    
    setTime(QTime(hour, minute, 0));
}

void TimePickerDialog::onNowClicked()
{
    setTime(QTime::currentTime());
}

void TimePickerDialog::onConfirm()
{
    emit timeSelected(m_currentTime);
    accept();
}

void TimePickerDialog::onCancel()
{
    reject();
}

void TimePickerDialog::accept()
{
    m_result = QDialog::Accepted;  // 1
    emit accepted();
    close();
}

void TimePickerDialog::reject()
{
    m_result = QDialog::Rejected;  // 0
    emit rejected();
    close();
}

int TimePickerDialog::exec()
{
    show();
    raise();
    activateWindow();
    
    QEventLoop eventLoop;
    connect(this, &TimePickerDialog::accepted, &eventLoop, &QEventLoop::quit);
    connect(this, &TimePickerDialog::rejected, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    
    return m_result;
}
